import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

  const routes = [
  {
    path: '/',
    name: 'MAINPAGE',
    component: ()=>import(/* webpackChunkName: "mianPage" */ '../views/index.vue'),
    redirect:'/home',
    children:[
      {
        path:'/home',
        component: ()=>import( '@/components/home/home.vue'),
      },
      {
        path:'/list',
        component: ()=>import( '@/components/list/list.vue'),
      },
      {
        path:'/jx',
        component: ()=>import( '@/components/jx/jx.vue'),
      },
      {
        path:'/cart',
        component: ()=>import( '@/components/cart/cart.vue'),
      },
      {
        path:'/user',
        component: ()=>import( '@/components/user/user.vue'),
      }
    ]
  },
  {
    path: '/info',
    name: 'info',
    component: () => import(/* webpackChunkName: "info" */ '../views/info.vue')
  },
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "login" */ '../views/login.vue')
  }
]

const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})
router.beforeEach((to,from,next)=>{
  let userStr = localStorage.getItem('jd_user'); //""  null
  let userInfo = userStr ? JSON.parse(userStr) : ({})
  let token = userInfo.token;
  // 实现页面 title的更改：  路由元信息
  if(token){
    if(to.path == '/login'){
      next('/')
    }else{
      next();
    }
  }else{
    // 证明 没登陆
    if(to.path == '/user'){
      next('/login')
    }else{
      next()
    }
  }
})

export default router
